# -*- coding: utf-8 -*-
from odoo import models, fields, api
from datetime import datetime
import time
from odoo.exceptions import ValidationError
from . import wechat_pay
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import logging
_logger = logging.getLogger(__name__)


class Registration_payment_wizard(models.TransientModel):
    """登记付款按钮触发，登记付款页面"""

    _name = 'wizard.registration_payment_wizard'

    total_amount = fields.Float(string=u'付款总额', readonly=True, compute='_compute_total_amount')
    date = fields.Datetime(string=u'付款日期', default=fields.datetime.now(), required=True, copy=False, readonly=True)
    num = fields.Char(string=u'单号', compute='_compute_num', readonly=True)
    payment_method = fields.Selection([('cash', u'现金支付'), ('wechat', u'微信支付')], string=u'付款方式', required=True)

    @api.depends('total_amount')
    def _compute_num(self):
        """获取当前应付款项对象， 通过应付款项登记付款按钮触发，
        将num字段传递给登记wizard前端，在这从wizard前端再次将信息提取出来"""
        for obj in self:
            obj.num = str(self.env.context.get('num'))

    @api.depends('num')
    def _compute_total_amount(self):
        for obj in self:
            obj.total_amount = float(self.env.context.get('total_amount'))

    def do_pay(self):
        if self.payment_method == 'wechat':
            payable_obj = self.env['sale_sys.account_payable'].search([('num', '=', self.num)])
            if payable_obj:
                open_id = payable_obj.user.wechat_id.open_id
                _logger.info(open_id)
                content = wechat_pay.wechat_pay(open_id, int(self.total_amount) * 100)  # todo 第一个参数 需要传递openid
                if content['is_successful']:
                    payable_obj.state = 'confirm'
                    payable_obj.payment_date = fields.Datetime.now()
                    payable_obj.user.withdraw += self.total_amount
                    # print content['return_msg'].decode() + '---------------支付时间' + content['payment_time'].decode()
                else:
                    text = content['err_code_des'].decode()
                    raise ValidationError('支付失败失败原因：%s' % (text))
            else:
                raise ValidationError('支付失败')
        if self.payment_method == 'cash':
            payable_obj = self.env['sale_sys.account_payable'].search([('num', '=', self.num)])
            payable_obj.state = 'confirm'
            payable_obj.payment_date = fields.Datetime.now()
            payable_obj.user.withdraw += self.total_amount

            Param = self.env()['ir.config_parameter']
            recipt = Param.get_param('recipt') or ''
            payable_2 = Param.get_param('payable_2') or ''
            recipt = int(recipt.encode("utf-8"))
            payable_2 = int(payable_2.encode("utf-8"))
            _logger.info(payable_2)
            _logger.info(recipt)
            self.env['money.recond'].create({
                'user': payable_obj.user.id,
                'sum': '+' + str(self.total_amount),
                'data': fields.Date.today()
            })
            journal = self.env['account.journal'].search([('name','=',u'其它操作')])
            journal = journal[0]
            move = self.env['account.move'].create({
                'journal_id': journal.id, #其他操作
                'date': datetime.today(),
                'name': 'INV' + str(datetime.today()),
                'state': 'posted',
            })
            label='/'
            move.line_ids.create({
            'move_id': move.id,
            'account_id': payable_2,      
            'debit': self.total_amount,      #借方金额
            'credit': 0.0,
            'date_maturity': datetime.today(),
            'partner_id': payable_obj.user.id,  #提现的人
            'name': label,
            })
            move.line_ids.create({
            'move_id': move.id,
            'account_id': recipt,   
            'debit': 0.0,      
            'credit': self.total_amount,
            'date_maturity': datetime.today(),
            'partner_id': payable_obj.user.id,
            'name': label,
            })